<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>JavaScript(2) | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="对象1、对象赋值person.name &#x3D; &quot;gyh&quot;&quot;gyh&quot;person.name&quot;gyh&quot;">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript(2)">
<meta property="og:url" content="https://curry3035.gitee.io/posts/50822/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="对象1、对象赋值person.name &#x3D; &quot;gyh&quot;&quot;gyh&quot;person.name&quot;gyh&quot;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2020-05-23T04:25:46.000Z">
<meta property="article:modified_time" content="2021-10-26T14:26:00.122Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="脚本语言">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/50822/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JavaScript(2)',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-10-26 22:26:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JavaScript(2)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-05-23T04:25:46.000Z" title="发表于 2020-05-23 12:25:46">2020-05-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-10-26T14:26:00.122Z" title="更新于 2021-10-26 22:26:00">2021-10-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaScript(2)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h4 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h4><h5 id="1、对象赋值"><a href="#1、对象赋值" class="headerlink" title="1、对象赋值"></a>1、对象赋值</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">person.<span class="property">name</span> = <span class="string">&quot;gyh&quot;</span></span><br><span class="line"><span class="string">&quot;gyh&quot;</span></span><br><span class="line">person.<span class="property">name</span></span><br><span class="line"><span class="string">&quot;gyh&quot;</span></span><br></pre></td></tr></table></figure>

<span id="more"></span>

<h5 id="2、使用一个不存在的对象属性，不会报错（undefined）"><a href="#2、使用一个不存在的对象属性，不会报错（undefined）" class="headerlink" title="2、使用一个不存在的对象属性，不会报错（undefined）"></a>2、使用一个不存在的对象属性，不会报错（undefined）</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">person.<span class="property">haha</span></span><br><span class="line"><span class="literal">undefined</span></span><br></pre></td></tr></table></figure>



<h5 id="3、动态的删减属性，通过delete删除对象的属性"><a href="#3、动态的删减属性，通过delete删除对象的属性" class="headerlink" title="3、动态的删减属性，通过delete删除对象的属性"></a>3、动态的删减属性，通过delete删除对象的属性</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">delete</span> person.<span class="property">name</span> </span><br><span class="line"><span class="literal">true</span></span><br></pre></td></tr></table></figure>



<h4 id="JavaScript-循环"><a href="#JavaScript-循环" class="headerlink" title="JavaScript 循环"></a>JavaScript 循环</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; cars.<span class="property">length</span>; i++) &#123; </span><br><span class="line">    text += cars[i] + <span class="string">&quot;&lt;br&gt;&quot;</span>;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line">等价于</span><br><span class="line"></span><br><span class="line">text += cars[<span class="number">0</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br><span class="line">text += cars[<span class="number">1</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br><span class="line">text += cars[<span class="number">2</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br><span class="line">text += cars[<span class="number">3</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br><span class="line">text += cars[<span class="number">4</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br><span class="line">text += cars[<span class="number">5</span>] + <span class="string">&quot;&lt;br&gt;&quot;</span>; </span><br></pre></td></tr></table></figure>

<h4 id="for-循环"><a href="#for-循环" class="headerlink" title="for 循环"></a>for 循环</h4><h5 id="for-循环的语法如下："><a href="#for-循环的语法如下：" class="headerlink" title="for 循环的语法如下："></a>for 循环的语法如下：</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">for (语句 1; 语句 2; 语句 3) &#123;</span><br><span class="line">     要执行的代码块</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="for-in-循环"><a href="#for-in-循环" class="headerlink" title="for  in  循环"></a>for  in  循环</h4><h5 id="JavaScript-for-in-语句遍历对象的属性："><a href="#JavaScript-for-in-语句遍历对象的属性：" class="headerlink" title="JavaScript for/in 语句遍历对象的属性："></a>JavaScript for/in 语句遍历对象的属性：</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var person = &#123;fname:&quot;Bill&quot;, lname:&quot;Gates&quot;, age:62&#125;; </span><br><span class="line"></span><br><span class="line">var text = &quot;&quot;;</span><br><span class="line">var x;</span><br><span class="line">for (x in person) &#123;</span><br><span class="line">    text += person[x];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Date"><a href="#Date" class="headerlink" title="Date"></a>Date</h4><h5 id="Date-对象方法"><a href="#Date-对象方法" class="headerlink" title="Date 对象方法"></a>Date 对象方法</h5><table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_Date.asp">Date()</a></td>
<td align="left">返回当日的日期和时间。</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_getDate.asp">getDate()</a></td>
<td align="left">从 Date 对象返回一个月中的某一天 (1 ~ 31)。</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_getDay.asp">getDay()</a></td>
<td align="left">从 Date 对象返回一周中的某一天 (0 ~ 6)。</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_getMonth.asp">getMonth()</a></td>
<td align="left">从 Date 对象返回月份 (0 ~ 11)。</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_getFullYear.asp">getFullYear()</a></td>
<td align="left">从 Date 对象以四位数字返回年份。</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.w3school.com.cn/jsref/jsref_getTime.asp">getTime()</a></td>
<td align="left">返回 1970 年 1 月 1 日至今的毫秒数。</td>
</tr>
<tr>
<td align="left"></td>
<td align="left"></td>
</tr>
</tbody></table>
<h4 id="javascript-Date-format-js日期格式化"><a href="#javascript-Date-format-js日期格式化" class="headerlink" title="javascript Date format(js日期格式化)"></a>javascript Date format(js日期格式化)</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 对Date的扩展，将 Date 转化为指定格式的String   </span></span><br><span class="line"><span class="comment">// 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   </span></span><br><span class="line"><span class="comment">// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   </span></span><br><span class="line"><span class="comment">// 例子：   </span></span><br><span class="line"><span class="comment">// (new Date()).Format(&quot;yyyy-MM-dd HH:mm:ss.S&quot;) ==&gt; 2006-07-02 08:09:04.423   </span></span><br><span class="line"><span class="comment">// (new Date()).Format(&quot;yyyy-M-d H:m:s.S&quot;)      ==&gt; 2006-7-2 8:9:4.18   </span></span><br><span class="line"><span class="title class_">Date</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">Format</span> = <span class="keyword">function</span>(<span class="params">fmt</span>)   </span><br><span class="line">&#123; <span class="comment">//author: meizz   </span></span><br><span class="line">  <span class="keyword">var</span> o = &#123;   </span><br><span class="line">    <span class="string">&quot;M+&quot;</span> : <span class="variable language_">this</span>.<span class="title function_">getMonth</span>()+<span class="number">1</span>,                 <span class="comment">//月份   </span></span><br><span class="line">    <span class="string">&quot;d+&quot;</span> : <span class="variable language_">this</span>.<span class="title function_">getDate</span>(),                    <span class="comment">//日   </span></span><br><span class="line">    <span class="string">&quot;h+&quot;</span> : <span class="variable language_">this</span>.<span class="title function_">getHours</span>(),                   <span class="comment">//小时   </span></span><br><span class="line">    <span class="string">&quot;m+&quot;</span> : <span class="variable language_">this</span>.<span class="title function_">getMinutes</span>(),                 <span class="comment">//分   </span></span><br><span class="line">    <span class="string">&quot;s+&quot;</span> : <span class="variable language_">this</span>.<span class="title function_">getSeconds</span>(),                 <span class="comment">//秒   </span></span><br><span class="line">    <span class="string">&quot;q+&quot;</span> : <span class="title class_">Math</span>.<span class="title function_">floor</span>((<span class="variable language_">this</span>.<span class="title function_">getMonth</span>()+<span class="number">3</span>)/<span class="number">3</span>), <span class="comment">//季度   </span></span><br><span class="line">    <span class="string">&quot;S&quot;</span>  : <span class="variable language_">this</span>.<span class="title function_">getMilliseconds</span>()             <span class="comment">//毫秒   </span></span><br><span class="line">  &#125;;   </span><br><span class="line">  <span class="keyword">if</span>(<span class="regexp">/(y+)/</span>.<span class="title function_">test</span>(fmt))   </span><br><span class="line">    fmt=fmt.<span class="title function_">replace</span>(<span class="title class_">RegExp</span>.<span class="property">$1</span>, (<span class="variable language_">this</span>.<span class="title function_">getFullYear</span>()+<span class="string">&quot;&quot;</span>).<span class="title function_">substr</span>(<span class="number">4</span> - <span class="title class_">RegExp</span>.<span class="property">$1</span>.<span class="property">length</span>));   </span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">var</span> k <span class="keyword">in</span> o)   </span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot;(&quot;</span>+ k +<span class="string">&quot;)&quot;</span>).<span class="title function_">test</span>(fmt))   </span><br><span class="line">  fmt = fmt.<span class="title function_">replace</span>(<span class="title class_">RegExp</span>.<span class="property">$1</span>, (<span class="title class_">RegExp</span>.<span class="property">$1</span>.<span class="property">length</span>==<span class="number">1</span>) ? (o[k]) : ((<span class="string">&quot;00&quot;</span>+ o[k]).<span class="title function_">substr</span>((<span class="string">&quot;&quot;</span>+ o[k]).<span class="property">length</span>)));   </span><br><span class="line">  <span class="keyword">return</span> fmt;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用方法：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">var time1 = new Date().format(&quot;yyyy-MM-dd HH:mm:ss&quot;);     </span><br><span class="line">  </span><br><span class="line">var time2 = new Date().format(&quot;yyyy-MM-dd&quot;);  </span><br></pre></td></tr></table></figure>



<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">now = <span class="keyword">new</span> <span class="title class_">Date</span>(<span class="variable constant_">XXXXXXXXX</span>)</span><br><span class="line">now.<span class="property">toLocaleString</span></span><br><span class="line">now.<span class="title function_">toLocaleString</span>()</span><br><span class="line"><span class="string">&quot;2020/2/18 上午10:49:35&quot;</span></span><br></pre></td></tr></table></figure>



<h4 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h4><h5 id="json-stringify"><a href="#json-stringify" class="headerlink" title="json.stringify()"></a>json.stringify()</h5><blockquote>
<p>JSON.stringify()的作用是将 JavaScript 对象转换为 JSON 字符串，而JSON.parse()可以将JSON字符串转为一个对象。</p>
<p>我用 JSON.stringify() 将对象 a 变成了字符串 c ，那么我就可以用 JSON.parse() 将字符串 c 还原成对象 a。</p>
</blockquote>
  <figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line"><span class="title class_">JSON</span>.<span class="title function_">stringify</span>(arr); <span class="comment">//&#x27;[1,2,3]&#x27;  =&gt; 将对象 arr 变成了字符串 arr。</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(arr); <span class="comment">//string  =&gt; 输出类型</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> string = <span class="string">&#x27;[1,2,3]&#x27;</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title class_">JSON</span>.<span class="title function_">parse</span>(string)) <span class="comment">//[1,2,3] =&gt; (3) [1, 2, 3]</span></span><br><span class="line">                                                <span class="number">0</span>: <span class="number">1</span></span><br><span class="line">                                                <span class="number">1</span>: <span class="number">2</span></span><br><span class="line">                                                <span class="number">2</span>: <span class="number">3</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="keyword">typeof</span> <span class="title class_">JSON</span>.<span class="title function_">parse</span>(string)) <span class="comment">//object</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>在使用 <strong>JSON.parse()</strong> 需要注意一点，由于此方法是将JSON字符串转换成对象，所以<strong>你的字符串必须符合JSON格式，即键值都必须使用双引号包裹</strong>：</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="string">&#x27;[&quot;1&quot;,&quot;2&quot;]&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> b = <span class="string">&quot;[&#x27;1&#x27;,&#x27;2&#x27;]&quot;</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title class_">JSON</span>.<span class="title function_">parse</span>(a));<span class="comment">// Array [1,2]</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title class_">JSON</span>.<span class="title function_">parse</span>(b));<span class="comment">// 报错</span></span><br></pre></td></tr></table></figure>



<p><strong>JSON.stringify()的几种妙用</strong></p>
<p><strong>1.判断数组是否包含某对象，或者判断对象是否相等。</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//判断数组是否包含某对象</span></span><br><span class="line"><span class="keyword">let</span> data = [</span><br><span class="line">    &#123;<span class="attr">name</span>:<span class="string">&#x27;echo&#x27;</span>&#125;,</span><br><span class="line">    &#123;<span class="attr">name</span>:<span class="string">&#x27;听风是风&#x27;</span>&#125;,</span><br><span class="line">    &#123;<span class="attr">name</span>:<span class="string">&#x27;天子笑&#x27;</span>&#125;,</span><br><span class="line">    ],</span><br><span class="line">    val = &#123;<span class="attr">name</span>:<span class="string">&#x27;天子笑&#x27;</span>&#125;;</span><br><span class="line"><span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data).<span class="title function_">indexOf</span>(<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(val)) !== -<span class="number">1</span>;<span class="comment">//true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//判断两数组/对象是否相等</span></span><br><span class="line"><span class="keyword">let</span> a = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],</span><br><span class="line">    b = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line"><span class="title class_">JSON</span>.<span class="title function_">stringify</span>(a) === <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(b);<span class="comment">//true</span></span><br></pre></td></tr></table></figure>

<p><strong>2.让localStorage/sessionStorage可以存储对象。</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//存</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">setLocalStorage</span>(<span class="params">key,val</span>)&#123;</span><br><span class="line">    <span class="variable language_">window</span>.<span class="property">localStorage</span>.<span class="title function_">setItem</span>(key,<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(val));</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//取</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getLocalStorage</span>(<span class="params">key</span>)&#123;</span><br><span class="line">    <span class="keyword">let</span> val = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(<span class="variable language_">window</span>.<span class="property">localStorage</span>.<span class="title function_">getItem</span>(key));</span><br><span class="line">    <span class="keyword">return</span> val;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//测试</span></span><br><span class="line"><span class="title function_">setLocalStorage</span>(<span class="string">&#x27;demo&#x27;</span>,[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]);</span><br><span class="line"><span class="keyword">let</span>  a = <span class="title function_">getLocalStorage</span>(<span class="string">&#x27;demo&#x27;</span>);<span class="comment">//[1,2,3]</span></span><br></pre></td></tr></table></figure>

<p><strong>3、JSON.stringify()与toString()的区别</strong></p>
<p><em><strong>这两者虽然都可以将目标值转为字符串，但本质上还是有区别的，比如</strong></em></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">let arr = [1,2,3];</span><br><span class="line">JSON.stringify(arr);//&#x27;[1,2,3]&#x27;</span><br><span class="line">arr.toString();//1,2,3</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/50822/">https://curry3035.gitee.io/posts/50822/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%84%9A%E6%9C%AC%E8%AF%AD%E8%A8%80/">脚本语言</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/22151/" title="JavaScript(3)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JavaScript(3)</div></div></a></div><div class="next-post pull-right"><a href="/posts/13958/" title="JavaScript(1)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript(1)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/63260/" title="JQuery"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-23</div><div class="title">JQuery</div></div></a></div><div><a href="/posts/22151/" title="JavaScript(3)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-23</div><div class="title">JavaScript(3)</div></div></a></div><div><a href="/posts/13958/" title="JavaScript(1)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-23</div><div class="title">JavaScript(1)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.</span> <span class="toc-text">对象</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1%E3%80%81%E5%AF%B9%E8%B1%A1%E8%B5%8B%E5%80%BC"><span class="toc-number">1.1.</span> <span class="toc-text">1、对象赋值</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2%E3%80%81%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E4%B8%8D%E5%AD%98%E5%9C%A8%E7%9A%84%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7%EF%BC%8C%E4%B8%8D%E4%BC%9A%E6%8A%A5%E9%94%99%EF%BC%88undefined%EF%BC%89"><span class="toc-number">1.2.</span> <span class="toc-text">2、使用一个不存在的对象属性，不会报错（undefined）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3%E3%80%81%E5%8A%A8%E6%80%81%E7%9A%84%E5%88%A0%E5%87%8F%E5%B1%9E%E6%80%A7%EF%BC%8C%E9%80%9A%E8%BF%87delete%E5%88%A0%E9%99%A4%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="toc-number">1.3.</span> <span class="toc-text">3、动态的删减属性，通过delete删除对象的属性</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JavaScript-%E5%BE%AA%E7%8E%AF"><span class="toc-number">2.</span> <span class="toc-text">JavaScript 循环</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#for-%E5%BE%AA%E7%8E%AF"><span class="toc-number">3.</span> <span class="toc-text">for 循环</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#for-%E5%BE%AA%E7%8E%AF%E7%9A%84%E8%AF%AD%E6%B3%95%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="toc-number">3.1.</span> <span class="toc-text">for 循环的语法如下：</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#for-in-%E5%BE%AA%E7%8E%AF"><span class="toc-number">4.</span> <span class="toc-text">for  in  循环</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#JavaScript-for-in-%E8%AF%AD%E5%8F%A5%E9%81%8D%E5%8E%86%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B1%9E%E6%80%A7%EF%BC%9A"><span class="toc-number">4.1.</span> <span class="toc-text">JavaScript for&#x2F;in 语句遍历对象的属性：</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Date"><span class="toc-number">5.</span> <span class="toc-text">Date</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Date-%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95"><span class="toc-number">5.1.</span> <span class="toc-text">Date 对象方法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#javascript-Date-format-js%E6%97%A5%E6%9C%9F%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-number">6.</span> <span class="toc-text">javascript Date format(js日期格式化)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JSON"><span class="toc-number">7.</span> <span class="toc-text">JSON</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#json-stringify"><span class="toc-number">7.1.</span> <span class="toc-text">json.stringify()</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>